package class04;

/**
 * @Auther: xw
 * @Create: 2022/3/11 10:29
 * @Description: 两个链表相加  // 测试链接：https://leetcode.com/problems/add-two-numbers/
 */
public class AddTwoNumbers {
    public static class ListNode {
        public int val;
        public ListNode next;

        public ListNode(int val) {
            this.val = val;
        }

        public ListNode(int val, ListNode next) {
            this.val = val;
            this.next = next;
        }
    }
    public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
        int len1 = getListLength(l1);
        int len2 = getListLength(l2);
        ListNode l = len1 >= len2 ? l1:l2;
        ListNode s = l == l1 ? l2 :l1;
        ListNode curl = l;
        ListNode curs = s;
        ListNode curLast = curl;
        int curNum = 0;
        int carry = 0;
        //短链表不为空
        while(curs != null ){
            curNum = curl.val + curs.val + carry;
            curl.val = (curNum % 10);
            carry = curNum / 10;
            curLast = curl;
            curl = curl.next;
            curs = curs.next;
        }
        //长链表不为空
        while(curl != null){
            curNum = curl.val + carry;
            curl.val = (curNum % 10);
            carry = curNum / 10 ;
            curLast = curl;
            curl = curl.next;
        }
        //进位符不等于0
        while(carry != 0){
            curLast.next = new ListNode(1);
        }
        return l;

    }

    /**
     * 得到链表的长度
     * @param head
     * @return
     */
    public static int getListLength(ListNode head){
        int length = 0;
        while(null != head){
            length++;
            head = head.next;
        }
        return length;
    }
}
